class TWsClient {
  constructor() {
    this.settings = {
      wsUrl: '',
      peerType: 'console',
      subAcs: ['common'],
      tag: {},
    }
    this.forceCloseFlag = false
    this._socket = null
    this._connected = false
    this._peerId = ''
    this.onlinePeers = {}
    this.info = {}
    this.status = {}
    this.events = {
      onConnectedChanged: (sender, data) => {},
      onSessionChanged: (sender, data) => {},
      onMsg: (sender, data) => {},
    }
  }
  get socket() {
    return this._socket
  }
  set socket(value) {
    return (this._socket = value)
  }
  get connected() {
    return this.socket && this.socket != null && this._connected
  }
  set connected(value) {
    if (this._connected != value) {
      this._connected = value
      this.trigger('onConnectedChanged', value)
    }
  }
  get peerId() {
    if (this._peerId == '') {
      this._peerId = 'pts_' + parseInt(new Date().getTime())
    }
    return this._peerId
  }
  init(wsUrl, peerType, subAcs, onConnectedChanged, onSessionChanged, onMsg, _tag = {}) {
    var me = this
    try {
      me.settings.wsUrl = wsUrl
      me.settings.peerType = peerType
      me.settings.subAcs = subAcs
      me.settings.tag = _tag
      if (onConnectedChanged && onConnectedChanged != null) {
        me.events.onConnectedChanged = onConnectedChanged
      }
      if (onSessionChanged && onSessionChanged != null) {
        me.events.onSessionChanged = onSessionChanged
      }
      if (onMsg && onMsg != null) {
        me.events.onMsg = onMsg
      }
    } catch (error) {
      console.log(error)
    }
  }
  trigger(eventCode, eventData) {
    var me = this
    try {
      var handler = me.events[eventCode]
      if (handler && handler != null) {
        handler(me, eventData)
      }
    } catch (error) {
      console.log(error)
    }
  }
  connect() {
    var me = this
    try {
      me.forceCloseFlag = false
      me.disconnect()
      var socket = new WebSocket(me.settings.wsUrl)
      socket.onopen = (event) => {
        console.log('WebSocket连接已建立')
        me.connected = true
        me.socket = socket
        var msg = me.getRegistMsg()
        socket.send(JSON.stringify(msg))
      }
      socket.onclose = (event) => {
        console.log('WebSocket连接已关闭')
        me.disconnect()
        if (!me.forceCloseFlag) {
          window.setTimeout(() => {
            me.connect()
          }, 3000)
        }
      }
      socket.onerror = (event) => {
        console.log('WebSocket连接失败')
      }
      socket.onmessage = (event) => {
        //console.log('收到消息：', event.data);
        try {
          var msg = JSON.parse(event.data)
          me.doOnMsg(msg)
        } catch (er) {
          console.log(er)
        }
      }
      me.socket = socket
      /*
          socket.addEventListener('open', (event) => {
              console.log('WebSocket连接已建立');
              me.connected = true;
              me.socket = socket;
              var msg = me.getRegistMsg();
              socket.send(JSON.stringify(msg));
          });
          // 监听消息接收事件
          socket.addEventListener('message', (event) => {
              //console.log('收到消息：', event.data);
              try {
                  var msg = JSON.parse(event.data);
                  me.doOnMsg(msg);
              } catch (er) {
                  console.log(er)
              }
          });
          // 监听连接关闭事件
          socket.addEventListener('close', (event) => {
              console.log('WebSocket连接已关闭');
              me.disconnect();
              if (!me.forceCloseFlag) {
                  window.setTimeout(() => {
                      me.connect()
                  }, 3000)
              }
          });
          // 监听连接关闭事件
          socket.addEventListener('error', (event) => {
              console.log('WebSocket连接失败');
          });
          this.socket = socket;
          socket.connect()
          */
    } catch (error) {
      console.log(error)
    }
  }
  getRegistMsg() {
    var me = this
    var msg = {
      ac: 'regist',
      data: {
        peerId: '',
        peerType: me.settings.peerType,
        subAcs: me.settings.subAcs,
        tag: me.settings.tag,
      },
    }
    try {
      msg.data.peerId = me.peerId
    } catch (er) {
      console.log(er)
    }
    return msg
  }
  disconnect() {
    var me = this
    try {
      if (me.socket && me.socket != null) {
        me.socket.close()
      }
    } catch (error) {
      console.log(error)
    } finally {
      me.connected = false
      me.socket = null
    }
  }
  doOnMsg(msg) {
    var me = this
    try {
      if (msg.ac == 'sessionChanged') {
        me.onlinePeers = msg.data
        me.trigger('onSessionChanged', me.onlinePeers)
      } else {
        me.trigger('onMsg', msg)
      }
    } catch (error) {
      console.log(error)
    }
  }
  sendData(dataObj) {
    var me = this
    try {
      if (me.connected) {
        me.socket.send(JSON.stringify(dataObj))
      }
    } catch (er) {
      console.log(er)
    }
  }
  sendMsg(msgType, msgData) {
    var me = this
    try {
      if (me.connected) {
        var msg = {
          ac: 'pub',
          data: {
            msgType: msgType,
            msgData: msgData,
          },
        }
        msg.data.peerId = me.peerId
        me.socket.send(JSON.stringify(msg))
      }
    } catch (er) {
      console.log(er)
    }
  }
}

export { TWsClient }
